package function;

import factory.SingleSqlParserFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CreateView {
    static public int entry_num = 10;

    // create table 表名(列名称1 数据类型1，列名称2 数据类型2)
    public static void createVw(String dbName, String tbName, List<String> tmp) throws DocumentException, IOException  {

        // 判断数据库是否为空
        if (IsLegal.isDatabaseEmpty()) {
            return;
        }
        String sql;
        StringBuilder sb = new StringBuilder();

        // 检查 ArrayList 是否至少有两个元素
        if (tmp.size() < 2) {
            return; // 或者返回一个合适的消息
        }

        // 添加第一个元素
        sb.append(tmp.get(1)); // 从第二个元素开始

        // 从第三个元素开始遍历，添加分隔符和元素
        for (int i = 2; i < tmp.size(); i++) {
            sb.append(',');
            sb.append(tmp.get(i));
        }

        // 返回合并后的字符串
        sql = sb.toString();
//        System.out.println(sql);


        List<List<String>> parameter_list = new ArrayList<List<String>>();
        try {
            parameter_list = SingleSqlParserFactory.generateParser(sql + " ENDOFSQL");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!contains(sql, "(select \\* from)(.+)")) {
            //表存在则打开配置文件
            File config_file = IsLegal.isTable(dbName, parameter_list.get(1).get(1));
            //解析配置文件
            SAXReader config_file_reader = new SAXReader();
            Document config_file_document = config_file_reader.read(config_file);
            Element table_message = config_file_document.getRootElement();
//        Element write_file_element = (Element) config_file_document.getRootElement().selectSingleNode(parameter_list.get(1).get(1));
//        Element insertable_element = (Element) config_file_document.getRootElement().selectSingleNode("insertables");

            for (int i = 1; i < parameter_list.get(0).size(); i++) {
                String columnName = parameter_list.get(0).get(i); // 列名

                // 获取列的类型（从根元素的属性中获取）
                String dataType = table_message.attributeValue(columnName);

                // 检查列是否有效
                if (dataType == null) {
                    System.out.println("创建失败：列 " + columnName + " 不存在于表 " + parameter_list.get(1).get(1) + "中");
                    return;
                }

            }
        }

        // 创建一张表的文件夹，逻辑上表示一张表
        File tableFile = new File("./mydatabase/" + dbName + "/" + tbName);
        if (!tableFile.exists()) {
            tableFile.mkdir();
        } else {
            System.out.println(tbName + " 视图已经存在或与现有表重名");
            return;
        }

        // 创建配置文件并设置根节点
        File table = new File("./mydatabase/" + dbName + "/" + tbName + "/" + tbName + "-config.xml");
        Document document = DocumentHelper.createDocument();
        Element rootElem = document.addElement(tbName + "s");


        // 保存sql语句
        rootElem.addElement("sql").setText(sql);

        // 写入操作
        writeIO(table, document);

        System.out.println(tbName + " 视图创建成功");


    }

    // 更新 document 树，写入外存
    public static void writeIO(File write_file, Document write_document) throws IOException {
        // 确定文件输出位置
        FileOutputStream outputStream = new FileOutputStream(write_file);
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        // 创建写入对象，写入 document 对象
        XMLWriter xmlWriter = new XMLWriter(outputStream, outputFormat);
        xmlWriter.write(write_document);
        // 关闭流
        xmlWriter.close();
    }

    // 删除创建失败时的表文件夹
    private static void deleteTableDirectory(File tableFile) {
        if (tableFile.exists()) {
            File[] files = tableFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    file.delete(); // 删除文件
                }
            }
            tableFile.delete(); // 删除文件夹
        }
    }

    private static boolean contains(String sql, String regExp) {
        Pattern pattern = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sql);
        return matcher.find();
    }
}